package edu.tjpu.share.service;

import java.io.File;
import java.util.HashMap;
import java.util.Random;
import java.util.concurrent.CountDownLatch;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.net.Uri;
import android.os.Binder;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.util.SparseArray;
import android.widget.Toast;
import edu.tjpu.share.R;
import edu.tjpu.share.app.Fields;
import edu.tjpu.share.newui.MainTabHost;
import edu.tjpu.share.task.DownloadTask;
import edu.tjpu.share.util.MIMEUtil;

public class DownloadService extends Service {

	public final static int UPDATE_DOWNLOAD_PERCENT = 3;
	public final static int START_DOWNLOAD = 2;
	public final static int DOWNLOAD_COMPLETE = 1;
	public final static int DOWNLOAD_FAILED = 0;
	private NotificationManager nm;
	private SparseArray<Notification> nArray;
	private SparseArray<PendingIntent> ptArray;
	private SparseArray<Intent> iArray;
	// private List<Integer> notificationIDList;
	private boolean overrifeFile = false;
	private CountDownLatch runningThreadNum = null;
	private Intent mIntentToStop;

	final static private String TAG = "DownloadService";
	final static public String DOWNLOAD_ACTION = "edu.tjpu.share.DownloadService";

	private DownloadBinder mBinder = new DownloadBinder();

	@Override
	public IBinder onBind(Intent intent) {
		return mBinder;
	}

	@Override
	public void onCreate() {
		nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		nArray = new SparseArray<Notification>();
		ptArray = new SparseArray<PendingIntent>();
		iArray = new SparseArray<Intent>();
		// notificationIDList = new ArrayList<Integer>();
		mIntentToStop = new Intent();
		mIntentToStop.setAction(DOWNLOAD_ACTION);
		mIntentToStop.setClass(DownloadService.this, DownloadService.class);
		super.onCreate();
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		if (intent != null) {
			if (runningThreadNum == null) {
				runningThreadNum = new CountDownLatch(intent.getIntExtra(
						"runningThreadNum", 1));
			}
			DownloadThread downloadThread = new DownloadThread(intent, startId,
					mStopServiceHandler);
			downloadThread.start();

			return START_STICKY;
		}
		return super.onStartCommand(intent, flags, startId);

	}

	// 子线程
	public class DownloadThread extends Thread {

		// 子线程记数器,记载着运行的线程数
		private Intent intent;
		private int startId;
		private Handler mStopServiceHandler;
		private Thread runThread = null;

		public DownloadThread(Intent intent, int startId,
				Handler mStopServiceHandler) {
			this.intent = intent;
			this.startId = startId;
			this.mStopServiceHandler = mStopServiceHandler;
		}

		@Override
		public void run() {
			runThread = currentThread();
			Log.d(TAG, "New Thread Started" + Thread.currentThread().getName());
			int notification_id = new Random(System.currentTimeMillis())
					.nextInt();
			// notificationIDList.add(notification_id);
			Log.w(TAG, "DownloadService get new  notification_id:"
					+ notification_id);
			Bundle bundle = intent.getExtras();
			HashMap<String, Object> map = (HashMap<String, Object>) bundle
					.getSerializable("values");
			Log.i(TAG, "DownloadService Received start id " + startId + ": "
					+ intent);
			download(map, notification_id, mDownloadThreadHandler);
		}

		private Handler mDownloadThreadHandler = new Handler() {

			@Override
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case DownloadService.DOWNLOAD_COMPLETE:
					mStopServiceHandler
							.sendEmptyMessage(DownloadService.DOWNLOAD_COMPLETE);
					if (runThread != null) {
						runThread.interrupt();
					}
					break;
				default:
					break;
				}
				super.handleMessage(msg);
			}

		};
	}

	private Handler mStopServiceHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case DownloadService.DOWNLOAD_COMPLETE:

				runningThreadNum.countDown();
				if (runningThreadNum.getCount() == 0) {
					DownloadService.this.stopService(mIntentToStop);
				}

				break;
			default:
				break;
			}
			super.handleMessage(msg);
		}

	};

	@Override
	public void onStart(Intent intent, int startId) {
		/*
		 * Bundle bundle = intent.getExtras(); map = (HashMap<String, Object>)
		 * bundle.getSerializable("values"); Log.i(TAG,
		 * "DownloadService Received start id " + startId + ": " + intent);
		 * Toast.makeText(this, "已启动后台服务下载。。", Toast.LENGTH_LONG).show();
		 * download();
		 */
		super.onStart(intent, startId);
	}

	@Override
	public void onDestroy() {
		/*
		 * Iterator<Integer> iterator = notificationIDList.iterator(); while
		 * (iterator.hasNext()) { int notificationID = iterator.next();
		 * nm.cancel(notificationID); }
		 */
		super.onDestroy();
	}

	@SuppressWarnings("unchecked")
	public void download(HashMap<String, Object> map, int notification_id,
			Handler mDownloadThreadHandler) {
		// 处理重名
		String filename = (String) map.get(Fields.FILE_NAME);
		String storeurl = (String) map.get(Fields.STORE_URL);
		Log.i(TAG, "DownloadService start download " + filename
				+ ". Will be stored in:" + storeurl);
		String theFile = Environment.getExternalStorageDirectory() + "/share"
				+ storeurl + filename;
		File file = new File(theFile);
		if (file.exists()) {
			if (overrifeFile) {
				file.delete();
			} else {
				String OnlyFileName = filename.substring(0,
						filename.lastIndexOf("."));
				String OnlyFileSub = filename.substring(
						filename.lastIndexOf("."), filename.length());
				filename = OnlyFileName + "(1)" + OnlyFileSub;
				theFile = Environment.getExternalStorageDirectory() + "/share"
						+ storeurl + filename;
				file = new File(theFile);
				int j = 2;
				while (file.exists()) {
					filename = OnlyFileName + "(" + (j++) + ")" + OnlyFileSub;
					theFile = Environment.getExternalStorageDirectory()
							+ "/share" + storeurl + filename;
					file = new File(theFile);
				}
			}
		}
		map.put(Fields.FILE_NAME, filename);
		// 处理重名

		Message msg = new Message();
		Bundle bundle = new Bundle();
		bundle.putString("filename", filename);
		bundle.putInt("notification_id", notification_id);
		msg.what = DownloadService.START_DOWNLOAD;
		msg.setData(bundle);
		downloadHandler.sendMessage(msg);

		map.put("mDownloadThreadHandler", mDownloadThreadHandler);
		map.put("notification_id", notification_id);
		map.put("downloadHandler", downloadHandler);
		new DownloadTask().execute(map);
	}

	private Handler downloadHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			Bundle bundle = msg.getData();
			String localFiledir = bundle.getString(Fields.FILE_URL);
			String filename = bundle.getString("filename");
			String realFileName = filename;
			if (filename.length() > 9) {
				filename = filename.substring(0, 9)
						+ "..."
						+ filename.substring(filename.length() - 4,
								filename.length());
			}

			Notification n;
			PendingIntent pt;
			Intent i;
			switch (msg.what) {
			case UPDATE_DOWNLOAD_PERCENT:
				n = nArray.get(bundle.getInt("notification_id"));
				n.setLatestEventInfo(DownloadService.this, "正在下载:" + filename,
						bundle.getInt("downloadPercent") + "%",
						ptArray.get(bundle.getInt("notification_id")));
				nm.notify(bundle.getInt("notification_id"), n);
				break;
			case START_DOWNLOAD:

				Toast.makeText(DownloadService.this, "已启动后台服务下载。。",
						Toast.LENGTH_SHORT).show();
				n = new Notification(R.drawable.downloading,
						"正在下载:" + filename, System.currentTimeMillis());
				i = new Intent(DownloadService.this, MainTabHost.class);
				i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
						| Intent.FLAG_ACTIVITY_NEW_TASK);
				iArray.put(bundle.getInt("notification_id"), i);
				pt = PendingIntent.getActivity(DownloadService.this, 0, i, 0);
				ptArray.put(bundle.getInt("notification_id"), pt);
				// 点击通知后的动作，这里是转回main 这个Acticity
				n.setLatestEventInfo(DownloadService.this, "Share-正在下载:"
						+ filename, "0%", pt);
				nArray.put(bundle.getInt("notification_id"), n);
				// 发出通知
				nm.notify(bundle.getInt("notification_id"), n);
				break;
			case DownloadService.DOWNLOAD_COMPLETE:
				n = nArray.get(bundle.getInt("notification_id"));
				n.defaults = Notification.DEFAULT_SOUND;// 铃声提醒

				Uri uri = Uri.fromFile(new File(localFiledir + realFileName));
				MIMEUtil mimeUtil = new MIMEUtil();
				PendingIntent ptt = PendingIntent.getActivity(
						DownloadService.this, 0,
						mimeUtil.getIntentToOpenFile(uri, realFileName), 0);
				if (realFileName.contains(".apk")) {
					n.setLatestEventInfo(DownloadService.this, "Share",
							filename + " 下载完成,点击安装。", ptt);
				} else {
					n.setLatestEventInfo(DownloadService.this, "Share",
							filename + " 下载成功！存储在：" + localFiledir, ptt);
				}
				nm.notify(bundle.getInt("notification_id"), n);
				Toast.makeText(DownloadService.this,
						realFileName + " 下载成功！存储在：" + localFiledir,
						Toast.LENGTH_SHORT).show();
				// 停止服务
				// stopService(i);
				break;
			case DownloadService.DOWNLOAD_FAILED:
				n = nArray.get(bundle.getInt("notification_id"));
				pt = ptArray.get(bundle.getInt("notification_id"));
				n.setLatestEventInfo(DownloadService.this, "Share", filename
						+ " 下载失败!", pt);
				nm.notify(bundle.getInt("notification_id"), n);
				Toast.makeText(DownloadService.this,
						"Share-" + realFileName + " 下载失败！", Toast.LENGTH_SHORT)
						.show();
				// stopService(i);
				break;
			default:

				// stopService(i);
			}
		}
	};

	public class DownloadBinder extends Binder {
		public DownloadService getService() {
			return DownloadService.this;
		}
	}

}
